<?php
/**
 * EPSON L4260 Series 简化打印解决方案
 * IP地址: 10.1.0.12
 * 
 * 此脚本提供稳定的打印方案：
 * 1. Windows系统打印（推荐且稳定）
 * 2. 网络连接诊断
 * 3. 打印机状态检查
 */

class SimplePrintSolution {
    private $printerIP = '10.1.0.12';
    private $printerPort = 631;
    private $printerName = 'EPSON L4260 Series';
    
    public function __construct() {
        echo "\n🖨️  EPSON L4260 Series 简化打印解决方案\n";
        echo "目标打印机: {$this->printerIP}:{$this->printerPort}\n";
        echo str_repeat('=', 60) . "\n\n";
    }
    
    /**
     * 主菜单
     */
    public function showMenu() {
        echo "请选择操作：\n";
        echo "1. Windows系统打印（推荐）\n";
        echo "2. 网络连接诊断\n";
        echo "3. 打印机状态检查\n";
        echo "4. 一键打印测试\n";
        echo "5. 退出\n\n";
        
        $choice = readline("请输入选择 (1-5): ");
        
        switch($choice) {
            case '1':
                $this->windowsPrint();
                break;
            case '2':
                $this->networkDiagnostic();
                break;
            case '3':
                $this->printerStatus();
                break;
            case '4':
                $this->quickPrintTest();
                break;
            case '5':
                echo "\n👋 再见！\n";
                exit(0);
            default:
                echo "\n❌ 无效选择，请重试。\n\n";
                $this->showMenu();
        }
    }
    
    /**
     * Windows系统打印（推荐方案）
     */
    public function windowsPrint() {
        echo "\n🖥️  Windows系统打印\n";
        echo str_repeat('-', 40) . "\n";
        
        try {
            // 检查打印机是否已安装
            echo "🔍 检查已安装的打印机...\n";
            $command = 'powershell -Command "Get-Printer | Where-Object {$_.Name -like \"*EPSON*\" -or $_.Name -like \"*L4260*\"} | Select-Object Name, DriverName, PortName, PrinterStatus"';
            $output = shell_exec($command);
            
            if (strpos($output, 'EPSON') !== false || strpos($output, 'L4260') !== false) {
                echo "✅ 找到EPSON打印机:\n";
                echo $output . "\n";
                
                // 创建测试文档
                $testContent = "EPSON L4260 Series 打印测试\n";
                $testContent .= str_repeat('=', 50) . "\n";
                $testContent .= "时间: " . date('Y-m-d H:i:s') . "\n";
                $testContent .= "IP地址: {$this->printerIP}\n";
                $testContent .= "打印方案: Windows系统打印\n";
                $testContent .= "状态: 测试成功\n";
                $testContent .= str_repeat('=', 50) . "\n";
                $testContent .= "\n这是一个测试页面，用于验证打印功能。\n";
                $testContent .= "如果您看到此页面，说明打印机工作正常。\n";
                
                $tempFile = tempnam(sys_get_temp_dir(), 'epson_test_') . '.txt';
                file_put_contents($tempFile, $testContent);
                
                echo "📄 创建测试文档: $tempFile\n";
                
                // 使用默认打印机打印
                echo "🖨️  正在发送打印任务...\n";
                $printCommand = "powershell -Command \"Start-Process notepad -ArgumentList '/p',\"$tempFile\"\" -Wait\"";
                $result = shell_exec($printCommand);
                
                echo "✅ 打印命令已执行\n";
                echo "💡 请检查打印机是否有输出\n";
                
                // 清理临时文件
                sleep(2); // 等待打印完成
                if (file_exists($tempFile)) {
                    unlink($tempFile);
                    echo "🗑️  临时文件已清理\n";
                }
                
            } else {
                echo "⚠️  未找到EPSON打印机\n";
                $this->showInstallInstructions();
            }
            
        } catch (Exception $e) {
            echo "❌ Windows打印失败: " . $e->getMessage() . "\n";
        }
        
        echo "\n" . str_repeat('=', 60) . "\n";
        $this->showMenu();
    }
    
    /**
     * 网络连接诊断
     */
    public function networkDiagnostic() {
        echo "\n🔍 网络连接诊断\n";
        echo str_repeat('-', 40) . "\n";
        
        $results = [];
        
        // 1. Ping测试
        echo "1. Ping测试到 {$this->printerIP}...\n";
        $pingResult = shell_exec("ping -n 3 {$this->printerIP}");
        if (strpos($pingResult, 'TTL') !== false) {
            echo "✅ Ping成功\n";
            $results['ping'] = true;
            // 提取延迟信息
            if (preg_match('/time=([0-9]+)ms/', $pingResult, $matches)) {
                echo "   延迟: {$matches[1]}ms\n";
            }
        } else {
            echo "❌ Ping失败\n";
            $results['ping'] = false;
        }
        
        // 2. 端口631测试
        echo "\n2. IPP端口631连接测试...\n";
        $connection = @fsockopen($this->printerIP, $this->printerPort, $errno, $errstr, 5);
        if ($connection) {
            echo "✅ 端口631连接成功\n";
            $results['ipp_port'] = true;
            fclose($connection);
        } else {
            echo "❌ 端口631连接失败: $errstr\n";
            $results['ipp_port'] = false;
        }
        
        // 3. HTTP端口80测试
        echo "\n3. HTTP端口80连接测试...\n";
        $httpConnection = @fsockopen($this->printerIP, 80, $errno, $errstr, 5);
        if ($httpConnection) {
            echo "✅ HTTP端口80连接成功\n";
            $results['http_port'] = true;
            fclose($httpConnection);
        } else {
            echo "❌ HTTP端口80连接失败\n";
            $results['http_port'] = false;
        }
        
        // 4. 网络路由测试
        echo "\n4. 网络路由测试...\n";
        $routeResult = shell_exec("tracert -h 5 {$this->printerIP}");
        if (strpos($routeResult, $this->printerIP) !== false) {
            echo "✅ 网络路由正常\n";
            $results['route'] = true;
        } else {
            echo "❌ 网络路由异常\n";
            $results['route'] = false;
        }
        
        // 5. 本机网络信息
        echo "\n5. 本机网络信息...\n";
        $ipconfig = shell_exec('ipconfig');
        if (preg_match('/IPv4.*?:\s*([0-9.]+)/', $ipconfig, $matches)) {
            echo "✅ 本机IP: {$matches[1]}\n";
            
            // 检查是否在同一网段
            $localIP = $matches[1];
            $localNetwork = implode('.', array_slice(explode('.', $localIP), 0, 3));
            $printerNetwork = implode('.', array_slice(explode('.', $this->printerIP), 0, 3));
            
            if ($localNetwork === $printerNetwork) {
                echo "✅ 与打印机在同一网段\n";
            } else {
                echo "⚠️  与打印机不在同一网段\n";
            }
        }
        
        // 诊断总结
        echo "\n📊 诊断总结:\n";
        $successCount = array_sum($results);
        $totalTests = count($results);
        echo "成功: $successCount/$totalTests 项测试\n";
        
        if ($results['ping'] && $results['route']) {
            echo "✅ 网络连接良好，推荐使用Windows系统打印\n";
        } else {
            echo "⚠️  网络连接存在问题，请检查网络配置\n";
        }
        
        echo "\n" . str_repeat('=', 60) . "\n";
        $this->showMenu();
    }
    
    /**
     * 打印机状态检查
     */
    public function printerStatus() {
        echo "\n🔍 打印机状态检查\n";
        echo str_repeat('-', 40) . "\n";
        
        // 检查Windows打印机状态
        echo "1. Windows打印机状态...\n";
        $command = 'powershell -Command "Get-Printer | Where-Object {$_.Name -like \"*EPSON*\" -or $_.Name -like \"*L4260*\"} | Format-Table Name, PrinterStatus, JobCount -AutoSize"';
        $output = shell_exec($command);
        
        if (trim($output)) {
            echo $output . "\n";
        } else {
            echo "❌ 未找到EPSON打印机\n";
        }
        
        // 检查打印队列
        echo "\n2. 打印队列状态...\n";
        $queueCommand = 'powershell -Command "Get-PrintJob | Where-Object {$_.PrinterName -like \"*EPSON*\" -or $_.PrinterName -like \"*L4260*\"} | Format-Table JobStatus, DocumentName, UserName -AutoSize"';
        $queueOutput = shell_exec($queueCommand);
        
        if (trim($queueOutput)) {
            echo $queueOutput . "\n";
        } else {
            echo "✅ 打印队列为空\n";
        }
        
        // 网络连接状态
        echo "\n3. 网络连接状态...\n";
        $connection = @fsockopen($this->printerIP, $this->printerPort, $errno, $errstr, 3);
        if ($connection) {
            echo "✅ 网络连接正常\n";
            fclose($connection);
        } else {
            echo "❌ 网络连接失败\n";
        }
        
        echo "\n" . str_repeat('=', 60) . "\n";
        $this->showMenu();
    }
    
    /**
     * 一键打印测试
     */
    public function quickPrintTest() {
        echo "\n🚀 一键打印测试\n";
        echo str_repeat('-', 40) . "\n";
        
        echo "正在执行完整测试流程...\n\n";
        
        // 1. 网络测试
        echo "[1/3] 网络连接测试...\n";
        $pingResult = shell_exec("ping -n 1 {$this->printerIP}");
        if (strpos($pingResult, 'TTL') !== false) {
            echo "✅ 网络连接正常\n";
        } else {
            echo "❌ 网络连接失败，无法继续\n";
            echo "\n" . str_repeat('=', 60) . "\n";
            $this->showMenu();
            return;
        }
        
        // 2. 打印机检查
        echo "\n[2/3] 打印机检查...\n";
        $printerCommand = 'powershell -Command "Get-Printer | Where-Object {$_.Name -like \"*EPSON*\" -or $_.Name -like \"*L4260*\"} | Select-Object -First 1 | Select-Object Name"';
        $printerOutput = shell_exec($printerCommand);
        
        if (strpos($printerOutput, 'EPSON') !== false || strpos($printerOutput, 'L4260') !== false) {
            echo "✅ 找到EPSON打印机\n";
        } else {
            echo "❌ 未找到EPSON打印机，请先安装驱动\n";
            $this->showInstallInstructions();
            echo "\n" . str_repeat('=', 60) . "\n";
            $this->showMenu();
            return;
        }
        
        // 3. 执行打印
        echo "\n[3/3] 执行打印测试...\n";
        $this->executeQuickPrint();
        
        echo "\n✅ 一键测试完成！\n";
        echo "\n" . str_repeat('=', 60) . "\n";
        $this->showMenu();
    }
    
    /**
     * 执行快速打印
     */
    private function executeQuickPrint() {
        $testContent = "EPSON L4260 Series 快速打印测试\n";
        $testContent .= str_repeat('=', 50) . "\n";
        $testContent .= "测试时间: " . date('Y-m-d H:i:s') . "\n";
        $testContent .= "打印机IP: {$this->printerIP}\n";
        $testContent .= "测试类型: 一键快速测试\n";
        $testContent .= str_repeat('=', 50) . "\n";
        $testContent .= "\n如果您看到此页面，说明打印功能正常工作。\n";
        $testContent .= "\n测试项目:\n";
        $testContent .= "✓ 网络连接\n";
        $testContent .= "✓ 打印机驱动\n";
        $testContent .= "✓ 打印队列\n";
        $testContent .= "✓ 文档输出\n";
        
        $tempFile = tempnam(sys_get_temp_dir(), 'epson_quick_') . '.txt';
        file_put_contents($tempFile, $testContent);
        
        echo "📄 创建测试文档\n";
        echo "🖨️  发送到打印机...\n";
        
        $printCommand = "powershell -Command \"Start-Process notepad -ArgumentList '/p',\"$tempFile\"\" -Wait\"";
        shell_exec($printCommand);
        
        echo "✅ 打印任务已发送\n";
        echo "💡 请检查打印机输出\n";
        
        // 清理
        sleep(2);
        if (file_exists($tempFile)) {
            unlink($tempFile);
        }
    }
    
    /**
     * 显示安装说明
     */
    private function showInstallInstructions() {
        echo "\n📋 打印机安装说明:\n";
        echo "1. 打开'设置' > '打印机和扫描仪'\n";
        echo "2. 点击'添加打印机或扫描仪'\n";
        echo "3. 选择'我需要的打印机不在列表中'\n";
        echo "4. 选择'使用TCP/IP地址或主机名添加打印机'\n";
        echo "5. 输入IP地址: {$this->printerIP}\n";
        echo "6. 端口名称: {$this->printerIP}\n";
        echo "7. 选择'EPSON L4260 Series'驱动程序\n";
        echo "8. 完成安装并设为默认打印机\n";
        
        echo "\n💡 或者使用自动安装命令:\n";
        echo "powershell -Command \"Add-Printer -Name 'EPSON L4260 Series' -DriverName 'EPSON L4260 Series' -PortName '{$this->printerIP}'\"\n";
    }
}

// 启动应用
echo "启动EPSON L4260 Series打印解决方案...\n";

try {
    $solution = new SimplePrintSolution();
    $solution->showMenu();
} catch (Exception $e) {
    echo "\n❌ 应用启动失败: " . $e->getMessage() . "\n";
    echo "\n💡 请检查PHP环境和权限设置\n";
}
?>